<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of common
 *
 * @author Tom Do
 */
Prado::using('Application.common.string');
Prado::using("Application.common.wideimage.WideImage");

class Common {
	//put your code here
	public function make_thumb($src,$dest,$desired_width,$desired_height=null)
	{	
		/* read the source image */
		
		//get image extension.
		$ext = Common::getExtension($src);
		//creates the new image using the appropriate function from gd library
		if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
			$source_image=imagecreatefromjpeg($src);		
		else if(!strcmp("png",$ext))
			$source_image=imagecreatefrompng($src);

		//$source_image = imagecreatefromjpeg($src);
		$width = imagesx($source_image);
		$height = imagesy($source_image);
		
		/* find the "desired height" of this thumbnail, relative to the desired width  */
		if ($desired_height == null)
			$desired_height = floor($height*($desired_width/$width));
			
		// calculating the part of the image to use for thumbnail
		if ($width > $height) {
			$y = 0;
		  	$x = ($width - $height) / 2;
		  	$smallestSide = $height;
		} else {
		  	$x = 0;
		  	$y = ($height - $width) / 2;
		  	$smallestSide = $width;
		}	
		
		/* create a new, "virtual" image */
		$virtual_image = imagecreatetruecolor($desired_width,$desired_height);
		
		/* copy source image at a resized size */
		//imagecopyresampled($virtual_image,$source_image,0,0,0,0,$desired_width,$desired_height,$width,$height);
		if ($desired_width == $desired_height)
			imagecopyresampled($virtual_image,$source_image,0,0,$x,$y,$desired_width,$desired_height,$smallestSide,$smallestSide);
		else if ($desired_width > $desired_height)
			imagecopyresampled($virtual_image,$source_image,0,0,$x,$y,$desired_width,$desired_height,$smallestSide+$x,$smallestSide);
		else	
			imagecopyresampled($virtual_image,$source_image,0,0,$x,$y,$desired_width,$desired_height,$smallestSide+$x,$smallestSide+$y);
			
		//imagecopyresampled($dst_image , $src_image , $dst_x , $dst_y , $src_x , $src_y , $dst_w , $dst_h , $src_w , $src_h )
		
		/* create the physical thumbnail image to its destination */
		if(!strcmp("png",$ext))
			imagepng($virtual_image,$dest,0);
		else
			imagejpeg($virtual_image,$dest,100);
	}
	
	public function make_thumb_square($src,$dest,$thumbSize)
	{	
		Common::make_thumb($src,$dest,$thumbSize,$thumbSize);
	}
	
	function getExtension($str) {
		$i = strrpos($str,".");
		if (!$i) { return ""; }
		$l = strlen($str) - $i;
		$ext = substr($str,$i+1,$l);
		return $ext;
	}
	
	public function check_dir($dirname)
	{	
		if (!file_exists($dirname))
			mkdir("$dirname", 0755);		
	}
	
	function saveFoodPlaceCuisine($sortOrder,$foodPlaceID,$cuisineID,$userID)
	{	
		$foodPlaceCuisineRecord = new FoodPlaceCuisineRecord;						
		$foodPlaceCuisineRecord->FoodPlaceID = $foodPlaceID;
		$foodPlaceCuisineRecord->CuisineID = $cuisineID;
		$foodPlaceCuisineRecord->SortOrder = $sortOrder;
		$foodPlaceCuisineRecord->CreateBy = $userID;
		$foodPlaceCuisineRecord->CreateDate = time();
		$foodPlaceCuisineRecord->save();
	}		
	
	public function saveFoodPlaceMainPhoto($source, $filePath, $hashImage, $hashStr, $imageExt)
	{	
		$image = WideImage::load($source);
						
		// scale the image to correct size of 560x325
		$resized = $image->resize(
			TPropertyValue::ensureInteger($this->Application->Parameters['FP_PHOTO_WIDTH']),
			TPropertyValue::ensureInteger($this->Application->Parameters['FP_PHOTO_WIDTH']),'outside')->crop('center', 'center',
				TPropertyValue::ensureInteger($this->Application->Parameters['FP_PHOTO_WIDTH']),
				TPropertyValue::ensureInteger($this->Application->Parameters['FP_PHOTO_HEIGHT']));
		$resized->saveToFile($filePath.$hashImage);

		// create food place photo thumbnail
		$resized = $image->resize(
			TPropertyValue::ensureInteger($this->Application->Parameters['FOOD_PLACE_PHOTO_THUMB_SIZE']),
			TPropertyValue::ensureInteger($this->Application->Parameters['FOOD_PLACE_PHOTO_THUMB_SIZE']),'outside')->crop('center', 'center',
				TPropertyValue::ensureInteger($this->Application->Parameters['FOOD_PLACE_PHOTO_THUMB_SIZE']),
				TPropertyValue::ensureInteger($this->Application->Parameters['FOOD_PLACE_PHOTO_THUMB_SIZE']));
		$resized->saveToFile($filePath.$hashStr.$this->Application->Parameters['FOOD_PLACE_PHOTO_THUMB_AFFFIX'].".".$imageExt);						
		
		// create food place listing photo	
		$resized = $image->resize(
			TPropertyValue::ensureInteger($this->Application->Parameters['FP_LIST_PHOTO_WIDTH']),
			TPropertyValue::ensureInteger($this->Application->Parameters['FP_LIST_PHOTO_WIDTH']),'outside')->crop('center', 'center',
				TPropertyValue::ensureInteger($this->Application->Parameters['FP_LIST_PHOTO_WIDTH']),
				TPropertyValue::ensureInteger($this->Application->Parameters['FP_LIST_PHOTO_HEIGHT']));
		$resized->saveToFile($filePath.$hashStr.$this->Application->Parameters['FP_LIST_PHOTO_AFFFIX'].".".$imageExt);						
								
		// create photo 0 thumb
		$resized = $image->resize(
			TPropertyValue::ensureInteger($this->Application->Parameters['PHOTO_LIST_THUMB_SIZE']),
			TPropertyValue::ensureInteger($this->Application->Parameters['PHOTO_LIST_THUMB_SIZE']),'outside')->crop('center', 'center',
				TPropertyValue::ensureInteger($this->Application->Parameters['PHOTO_LIST_THUMB_SIZE']),
				TPropertyValue::ensureInteger($this->Application->Parameters['PHOTO_LIST_THUMB_SIZE']));
		$resized->saveToFile($filePath.$hashStr.$this->Application->Parameters['PHOTO_LIST_AFFFIX'].".".$imageExt);
	}
	
	function savePhoto($photo, $filePath, $sortOrder, $foodPlaceID, $userID)
	{
		$hashStr=md5(uniqid(time()));
		$imageExt=strtolower(array_pop(explode('.',$photo->FileName)));
		$hashImage=$hashStr.'.'.$imageExt;
		$source = $filePath.$hashStr.$this->Application->Parameters['AFFFIX_ORG'].'.'.$imageExt;
		$photo->saveAs($source, true);
		
		$photoRecord = new PhotoRecord;					
		$photoRecord->PhotoFile = $hashImage;
		$photoRecord->FoodPlaceID = $foodPlaceID;
		$photoRecord->SortOrder = $sortOrder;
		$photoRecord->CreateBy = $userID;
		$photoRecord->CreateDate = time();			
		$photoRecord->save();													
		
		// scale the image to correct size of 560x325
		$image = WideImage::load($source);
		$resized = $image->resize(
			TPropertyValue::ensureInteger($this->Application->Parameters['FP_PHOTO_WIDTH']),
			TPropertyValue::ensureInteger($this->Application->Parameters['FP_PHOTO_WIDTH']),'outside')->crop('center', 'center',
				TPropertyValue::ensureInteger($this->Application->Parameters['FP_PHOTO_WIDTH']),
				TPropertyValue::ensureInteger($this->Application->Parameters['FP_PHOTO_HEIGHT']));
		$resized->saveToFile($filePath.$hashImage);
		
		// create thumbnail		
		$resized = $image->resize(
			TPropertyValue::ensureInteger($this->Application->Parameters['PHOTO_LIST_THUMB_SIZE']),
			TPropertyValue::ensureInteger($this->Application->Parameters['PHOTO_LIST_THUMB_SIZE']),'outside')->crop('center', 'center',
				TPropertyValue::ensureInteger($this->Application->Parameters['PHOTO_LIST_THUMB_SIZE']),
				TPropertyValue::ensureInteger($this->Application->Parameters['PHOTO_LIST_THUMB_SIZE']));
		$resized->saveToFile($filePath.$hashStr.$this->Application->Parameters['PHOTO_LIST_AFFFIX'].".".$imageExt);
		
		/*$dest = $filePath.$hashStr.$this->Application->Parameters['PHOTO_LIST_AFFFIX'].".".$imageExt;						
		Common::make_thumb_square($source,$dest,
			TPropertyValue::ensureInteger($this->Application->Parameters['PHOTO_LIST_THUMB_SIZE']));*/
	}
	
	function generateHash($bookingId,$userId)
	{
		$bookingId = base64_encode($this->Application->SecurityManager->hashData($bookingId));
		$userId = base64_encode($this->Application->SecurityManager->hashData($userId));
		$hash = array($bookingId,$userId);
		return $this->Application->SecurityManager->hashData(serialize($hash));
	}
	
	function getDate ($date, $g)
	{		
		$tok = strtok($date, "-");
		for ($i = 0; $tok; $i++) 
		{
 			if ($i == 0)
 				$year = $tok;
 			else if ($i == 1)
 				$month = $tok; 
 			else if ($i == 2)
 				$day = $tok; 
 				
 			$tok = strtok("-");
		}
		if ($month < 10)
			$month = substr($month, 1);
		if ($day < 10)
			$day = substr($day, 1);
			
		if ($g == 'd')
			return $day;
		else if ($g == 'm')
			return $month;	
		else if ($g == 'y')
			return $year;	
		else	
			return ($month . "/" . $day . "/" . $year);
	}
	
	
	function getMonthName($monthNum)
	{	
		$stringmonth = '';
		
		switch($monthNum)
		{
			case "1" :
				$stringmonth = "Jan";
				break;
			case "2" :
				$stringmonth = "Feb";
				break;
			case "3" :
				$stringmonth = "Mar";
				break;
			case "4" :
				$stringmonth = "Apr";
				break;
			case "5" :
				$stringmonth = "May";
				break;
			case "6" :
				$stringmonth = "Jun";
				break;
			case "7" :
				$stringmonth = "Jul";
				break;
			case "8" :
				$stringmonth = "Aug";
				break;
			case "9" :
				$stringmonth = "Sep";
				break;
			case "10" :
				$stringmonth = "Oct";
				break;
			case "11" :
				$stringmonth = "Nov";
				break;
			case "12" :
				$stringmonth = "Dec";
		} 
		
		return $stringmonth;
	}
	
	function checkAdmin($user) {
		//if (in_array($user->Email, $pieces = explode(",",$this->Application->Parameters['ADMIN_EMAILS'])))
		if ($user->Status == 2 || in_array($user->Email, $pieces = explode(",",$this->Application->Parameters['ADMIN_EMAILS'])))
			return true;
		else
			return false;
	}
		
	// existing
	function chars($text_, $charnum, $more='') {
		$text_ = String::trim($text_);
		if(($charnum >0) && (String::strlen($text_) > $charnum)) return String::substr($text_,0,$charnum).(($more=='')?"&hellip;":$more);
		else return $text_;
	}	
	
	function showOrdinal($num) {
		// first convert to string if needed
		$the_num = (string) $num;
		// now we grab the last digit of the number
		$last_digit = substr($the_num, -1, 1);
		// if the string is more than 2 chars long, we get
		// the second to last character to evaluate
		if (strlen($the_num)>1) {
			$next_to_last = substr($the_num, -2, 1);
		} else {
			$next_to_last = "";
		}
		// now iterate through possibilities in a switch
		switch($last_digit) {
			case "1":
				// testing the second from last digit here
				switch($next_to_last) {
					case "1":
						$the_num.="th";
						break;
					default:
						$the_num.="st";
				}
				break;
			case "2":
				// testing the second from last digit here
				switch($next_to_last) {
					case "1":
						$the_num.="th";
						break;
					default:
						$the_num.="nd";
				}
				break;
			// if last digit is a 3
			case "3":
				// testing the second from last digit here
				switch($next_to_last) {
					case "1":
						$the_num.="th";
						break;
					default:
						$the_num.="rd";
				}
				break;
			// for all the other numbers we use "th"
			default:
				$the_num.="th";
		}
	
		// finally, return our string with it's new suffix
		return $the_num;
	}
	
	/** 
	 * Cut string to n symbols and add delim but do not break words. 
	 * 
	 * Example: 
	 * <code> 
	 *  $string = 'this sentence is way too long'; 
	 *  echo neat_trim($string, 16); 
	 * </code> 
	 * 
	 * Output: 'this sentence is...' 
	 * 
	 * @access public 
	 * @param string string we are operating with 
	 * @param integer character count to cut to 
	 * @param string|NULL delimiter. Default: '...' 
	 * @return string processed string 
	 **/ 
	function neatTrim($str, $n, $delim='...') { 
	   $len = strlen($str); 
	   if ($len > $n) { 
		   preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches); 
		   return rtrim($matches[1]) . $delim; 
	   } 
	   else { 
		   return $str; 
	   } 
	} 
}
?>
